import random

from models import User
from models import Message
from utils import log, response_with_headers, redirect, http_response
from utils import template

message_list = []

# session 可以在服务器端实现过期功能
session = {
    'session id': {
        'username': 'gua',
    }
}


def current_user(request):
    session_id = request.cookies.get('user', '')
    # 被替换username = session.get(session_id, '【游客】')
    user_id = session.get(session_id, '-1')
    u = User.find_by(id=user_id)
    return u


def random_str():
    """
    生成一个随机的字符串
    """
    seed = 'abcdef'
    s = ''
    for i in range(16):
        # 这里 len(seed) - 2 是因为我懒得去翻文档来确定边界了
        random_index = random.randint(0, len(seed) - 2)
        s += seed[random_index]
    return s


def route_login(request):
    """
    html页面：提交表单request,form-> Server ->routes：form = request.form()-> User.new(form)->渲染html
    """
    headers = {}
    log('login, cookies', request.cookies)
    # username = current_user(request)
    if request.method == 'POST':
        form = request.form()
        # form是dict
        # u = User.new(form)
        u = User(form)
        if u.validate_login():
            user = User.find_by(username=u.username)
            session_id = random_str()
            # 替换原来的session[session_id] = user.username
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            # result = '登录成功'
            return redirect('/', headers)
    # 显示登录页面
    body = template('login.html')
    return http_response(body, headers=headers)


def route_register(request):
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_register():
            u.save()
            return redirect('/login')
        else:
            return redirect('/register')
    # 显示注册页面
    body = template('register.html')
    return http_response(body)


def route_admin_users(request):
    u = current_user(request)
    if u is not None and u.is_admin():
        us = User.all()
        body = template('admin_users.html', users=us)
        return http_response(body)
    else:
        return redirect('/login')


route_dict = {
    '/login': route_login,
    '/register': route_register,
    '/admin/users': route_admin_users,
}
